//
//  ZButton.m
//  ZPlayer
//
//  Created by Zed Link on 5/12/2016.
//  Copyright © 2016 ZED. All rights reserved.
//

#import "ZVerticalButton.h"

@interface ZVerticalButton () {
    CGSize _titleSize;
    CGFloat _imageWidth;
    CGFloat _imageHeight;
}

@end

@implementation ZVerticalButton

+ (instancetype)zVerticalButtonWithTitle:(NSString *)title fontSize:(CGFloat)size color:(UIColor *)color image:(NSString *)imageName
{
    return [[self alloc] initWithTitle:title fontSize:size color:color image:imageName];
}

- (instancetype)initWithTitle:(NSString *)title fontSize:(CGFloat)size color:(UIColor *)color image:(NSString *)imageName
{
    if (self = [super init]) {
        [self setTitleColor:color forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont systemFontOfSize:size weight:UIFontWeightRegular];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        [self setTitle:title andImage:[UIImage imageNamed:imageName]];
        _titleSize = [title sizeWithAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:size]}];
    }
    return self;
}

- (void)setTitle:(NSString *)title andImage:(UIImage *)image
{
    [self setTitle:title forState:UIControlStateNormal];
    [self setImage:image forState:UIControlStateNormal];
}

/** 图片位置处理 */
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
//    CGFloat totalHeight = self.currentImage.size.height + _space + _titleSize.height;
//    CGFloat x = (contentRect.size.width - self.currentImage.size.width) / 2;
//    CGFloat y = (contentRect.size.height - totalHeight) / 2;
//    
//    return CGRectMake(x, y, self.currentImage.size.width, self.currentImage.size.height);
    
    BOOL widthEnough = contentRect.size.width > self.currentImage.size.width;
    _imageWidth = widthEnough ? self.currentImage.size.width : contentRect.size.width;
    _imageHeight = widthEnough ? self.currentImage.size.height : contentRect.size.width;
    
    CGFloat totalHeight = _imageHeight + _space + _titleSize.height;
    CGFloat x = 0;
    if (widthEnough) {
        x = (contentRect.size.width - self.currentImage.size.width) / 2;
    }
    CGFloat y = (contentRect.size.height - totalHeight) / 2;
    
    return CGRectMake(x, y, _imageWidth, _imageHeight);
}

/** 标题位置处理 */
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGFloat totalHeight = (_imageHeight + _space + _titleSize.height);
    CGFloat imageY = (contentRect.size.height - totalHeight) / 2;
    CGFloat y = imageY + _imageHeight + _space;
    return CGRectMake(0, y, contentRect.size.width, _titleSize.height);
}

@end
